在SpringBoot的组件自动扫描加载中怎么样去exclude classes/packages呢?我们可以使用@ComponentScan
的excludeFilters
来实现。
实现方法一
ExcludedService.java
package cn.webfuse.service.exclude;
import org.springframework.stereotype.Service;
@Service
public class ExcludedService {
public ExcludedService() {
System.out.println("Instantiating " + getClass().getSimpleName());
}
}
IncludedService.java
package cn.webfuse.service.include;
import org.springframework.stereotype.Service;
@Service
public class IncludedService {
public IncludedService() {
System.out.println("Instantiating " + getClass().getSimpleName());
}
}
Application.java
@SpringBootApplication
@ComponentScan(
excludeFilters = @ComponentScan.Filter(
type = FilterType.REGEX,
pattern = "cn.webfuse.service.exclude.*"))
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
运行只得到IncludedService
的打印。
实现方法二
IgnoreDuringScan.java
package cn.webfuse.annotation;
public @interface IgnoreDuringScan {
}
ExcludedConfig.java
package cn.webfuse.config.exclude;
import cn.webfuse.annotation.IgnoreDuringScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@IgnoreDuringScan
public class ExcludedConfig {
public ExcludedConfig() {
System.out.println("Instantiating " + getClass().getSimpleName());
}
}
IncludedConfig.java
package cn.webfuse.config.include;
import org.springframework.context.annotation.Configuration;
@Configuration
public class IncludedConfig {
public IncludedConfig() {
System.out.println("Instantiating " + getClass().getSimpleName());
}
}
Application.java
@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(IgnoreDuringScan.class))
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}